package algorithm;

import java.util.Arrays;

public class BubbleSort {


    public static void main(String[] args) {
        int[] arr = {4,1,8,6,5,7};
        bubbleSort3(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void bubbleSort(int[] arr) {
        if (arr == null || arr.length == 0) {
            return;
        }
        // 内层是否发生了交互，减少外层循环，优化时间复杂度为O(n)
        boolean doSwap = false ;
        // 减少内层循环的
        int sortBorder = arr.length - 1;
        int lastSwapIndex = 0;
        // 外层循环控制排序多少次
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < sortBorder; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    lastSwapIndex = j;
                    doSwap = true;
                }
            }
            // 排序边界
            sortBorder = lastSwapIndex;
            // 没有发生交换，外层不用继续循环
            if (!doSwap) {
                return;
            }
        }
    }

    public static void bubbleSort2(int[] arr){
        boolean doSwap = false;
        int lastSwapIndex = 0;
        int sortBoarder = arr.length - 1;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < sortBoarder; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    lastSwapIndex = j;
                    doSwap = true;
                }
            }
            sortBoarder = lastSwapIndex;
            if (!doSwap) {
                return;
            }
        }
    }

    public static void bubbleSort3(int[] arr) {

        int sortBoarder = arr.length - 1;
        int lastSwapIndex = 0;
        boolean doSwap = false;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < sortBoarder; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    doSwap = true;
                    lastSwapIndex = j;
                }
            }
            sortBoarder = lastSwapIndex;
            if (!doSwap) {
                return;
            }
        }
    }
}
